<template>
  <div class="u-page mai-conversation-add">
    <!-- 🎯 页面顶部导航栏 -->
    <div class="conversation_head_weichat">
      <!-- 返回按钮 -->
      <div @click="goBack()" class="conversation_head_back_button_weichat">
        <img src="/static/icon/common/return-icon.png" />
      </div>

      <!-- 页面标题 -->
      <div class="conversation_head_title_weichat">添加朋友 / 申请加群</div>
    </div>
	  <!-- 自动搜索 -->
	  <div class="search">
		<div class="searh-input">
			  <u--input
			    placeholder="搜索 账号/手机号/群名称/群ID"
			    border="surround"
			    v-model="phone"
			  ></u--input>
		  </div>
		  <div class="search-button">
		    <u-button type="success" text="确定" @click="findFriendAndQun" />
		  </div>
	  </div>

<!-- 如果无结果 -->
<template v-if="isContactSearchNoResult">
  <div class="search-result-empty">
    <u-icon name="info-circle" color="#999" size="40"></u-icon>
    <p class="empty-text">未找到相关结果</p>
  </div>
</template>

<!-- 如果有搜索结果 -->
<template v-else>
  <div class="search-result-list">
    <div class="friend-item" v-for="(item, index) in contactSearchResult.user.list" :key="index">
      <img class="avatar" :src="item.avatar || '/static/default-avatar.png'" alt="头像" />
      <div class="user-info">
        <p class="username">{{ item.nick || item.userID }}</p>
        <p class="userid">ID: {{ item.userID }}</p>
      </div>
      <u-button :customStyle="{ width: '100px', fontSize: '30px', height: '36px', borderRadius: '6px' }" text="添加" type="primary" size="mini" @click="addFriend(item.userID)" />
    </div>
	<div class="friend-item" v-for="(group, index) in contactSearchResult.group.list" :key="'g' + index">
	  <img class="avatar" :src="group.avatar || '/static/default-group.png'" alt="群头像" />
	  <div class="user-info">
	    <p class="username">{{ group.name || group.groupID }}</p>
	    <p class="userid">群ID: {{ group.groupID }}</p>
	  </div>
	  <u-button :customStyle="{ width: '100px', fontSize: '24px', height: '36px', borderRadius: '6px' }" text="申请加群" type="primary" size="mini" @click="joinGroup(group.groupID)" />
	</div>

  </div>
</template>

	
  </div>
</template>
<script lang="ts" setup>
	// 📦 导入腾讯云IM相关模块
	import {
	  TUITranslateService,  // 翻译服务
	  TUIStore,            // 状态管理
	  StoreName,           // 存储名称枚举
	  IGroupModel,         // 群组模型接口
	  TUIFriendService,    // 好友服务
	  TUIGroupService,
	  Friend,              // 好友类型
	  FriendApplication,   // 好友申请类型
	  TUIUserService,      // 用户服务
	} from '@tencentcloud/chat-uikit-engine';
import { TUIGlobal } from '@tencentcloud/universal-api';
// 📦 导入Vue 3组合式API
import { 
  ref, 
  computed, 
  onMounted, 
  onUnmounted, 
  provide 
} from '/TUIKit/adapter-vue';
/** 联系人搜索结果 */
const contactSearchResult = ref();
// 定义变量
const phone = ref()
const hasResult = ref(false)
/** 判断联系人搜索是否无结果 */
const isContactSearchNoResult = computed((): boolean => {
  return (
    !contactSearchResult?.value?.user?.list[0] &&
    !contactSearchResult?.value?.group?.list[0]
  );
});

const findFriendAndQun = () => {
  const keyword = phone.value.trim().toLowerCase();
  if (!keyword) return uni.showToast({ title: '请输入关键词', icon: 'none' });

  uni.request({
    url: uni.$baseUrl +'/home/im/search_user',
    method: 'POST',
    data: {
		groupid:uni.getStorageSync('userAppInfo').groupid,
		keyword: keyword,
    },
    success: (res) => {
      if (res.data.code === 200) {
        contactSearchResult.value = res.data.data;
      } else {
        contactSearchResult.value = { user: { list: [] }, group: { list: [] } };
        uni.showToast({ title: res.data.msg || '搜索失败', icon: 'none' });
      }
    },
    fail: () => {
      uni.showToast({ title: '网络错误', icon: 'none' });
    },
  });
};


const addFriend = async (userID: string) => {
  try {
    const res = await TUIFriendService.addFriend({
      to: userID,
      source: 'AddSource_Type_Web', // 或 'AddSource_Type_Unknow' / 'AddSource_Type_Android' 等
      wording: '你好，我想加你为好友',
    });

    const { code, data } = res;

    if (code === 0 && data?.code === 0) {
      uni.showToast({ title: '好友请求已发送', icon: 'success' });
    } else if (data?.code === 30539) {
      uni.showToast({ title: '请求已发送，等待对方处理', icon: 'none' });
    } else if (data?.code === 30515) {
      uni.showToast({ title: '你们已经是好友啦', icon: 'none' });
    } else {
      uni.showToast({ title: `添加失败，code: ${data?.code}`, icon: 'none' });
    }
  } catch (err) {
    console.error('添加好友失败:', err);
    uni.showToast({ title: '添加好友失败', icon: 'none' });
  }
};




const joinGroup = async (groupID: string) => {
  try {
    const res = await TUIGroupService.joinGroup({
      groupID,
      applyMessage: '你好，我想加入此群',
    });

    if (res.code === 0) {
      uni.showToast({ title: '入群请求已发送', icon: 'success' });
    } else if (res.code === 10013) {
      uni.showToast({ title: '你已经在群里了', icon: 'none' });
    } else {
      uni.showToast({ title: `加群失败 code: ${res.code}`, icon: 'none' });
    }
  } catch (err) {
    console.error('申请加群失败:', err);
    uni.showToast({ title: '申请加群失败', icon: 'none' });
  }
};

/**
 * 返回上一页
 */
const goBack = (): void => {
  // TODO: 实现返回逻辑
  uni.navigateBack();
};
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style scoped>
/* 🏠 主容器样式 */
.mai-conversation-add {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #f9f9f9;
  overflow: hidden;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, sans-serif;
}

/* 🎯 顶部导航栏样式 */
.conversation_head_weichat {
  display: flex;
  align-items: center;
  padding: env(safe-area-inset-top) 12px 0 12px; /* 适配安全区域 */
  height: calc(44px + env(safe-area-inset-top));
  background-color: #f5f5f5;
  border-bottom: 1px solid #e5e5e5;
}

/* 🔙 返回按钮图标样式 */
.conversation_head_back_button_weichat img {
  width: 24px;
  height: 24px;
}

/* 🔙 返回按钮容器样式 */
.conversation_head_back_button_weichat {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 40px;
}

/* 🔍 搜索区域样式 */
.search {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
}

.searh-input {
  flex: 1;
}

.search-button {
  flex-shrink: 0;
}

/* 📝 标题样式 */
.conversation_head_title_weichat {
  font-size: 16px;
  font-weight: 600;
  line-height: 44px;
  color: #222;
  flex: 1;
  text-align: center;

}

/* 搜索结果样式 */
.search-result-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 80px;
  color: #999;

  .empty-text {
    margin-top: 10px;
    font-size: 14px;
  }
}

.search-result-list {
  margin-top: 12px;
  padding: 0 12px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;

  .avatar {
    width: 44px;
    height: 44px;
    border-radius: 8px;
    margin-right: 12px;
  }

  .user-info {
    flex: 1;

    .username {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .userid {
      font-size: 12px;
      color: #888;
      margin-top: 4px;
    }
  }
}
</style>
